# controllers/auth.py
from functools import wraps
from flask import request, make_response

def requires_auth(f):
    """Basic Auth装饰器"""
    @wraps(f)
    def decorated(*args, **kwargs):
        # 首先检查新的会话认证
        from flask import session
        from models.database import SessionLocal
        from models.user import User
        
        if 'user_id' in session:
            db = SessionLocal()
            try:
                user = db.query(User).filter(User.id == session['user_id'], User.is_active == True).first()
                if user:
                    request.current_user = user
                    return f(*args, **kwargs)
            finally:
                db.close()
        
        # 如果会话认证失败，回退到基本认证
        auth = request.authorization
        # 从应用配置中获取用户名和密码
        if hasattr(f, 'app') and f.app:
            username = f.app.config.get('ADMIN_USERNAME', 'admin')
            password = f.app.config.get('ADMIN_PASSWORD', 'admin')
        else:
            # 默认值
            username = 'admin'
            password = 'admin'
            
        if not auth or not (auth.username == username and auth.password == password):
            resp = make_response('Login required', 401)
            resp.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
            return resp
        return f(*args, **kwargs)
    return decorated